import { observable, action } from 'mobx';
import API from '../../apis';

class SearchStore {
    @observable
    state = {
        init: {
            loading: true,
            datas: [],
            showColumns: [],
            pageIndex: 1,
            total: 0,
            totalWidth: 0,
        }
    }
    windowDimensions = observable.struct({
        width: jQuery(window).width(),
        height: jQuery(window).height()
    });
    constructor() {
        jQuery(window).resize(() => {
            this.windowDimensions = this.getWindowDimensions();
        })
    }
    getWindowDimensions() {
        return observable.struct({
            width: jQuery(".coms-mode-search-scroll-wrap").width(),
            height: jQuery(".coms-mode-search-scroll-wrap").height()
        });
    }
    @action
    update = (guid, payload) => {
        this.state = {
            ...this.state,
            [guid]: {
                ...(this.state[guid] || this.state.init),
                ...payload
            }
        }
    }
    @action
    dataKey = (guid, dataKey) => {
        this.update(guid, { dataKey })
        this.datas(guid, { guid, dataKey });
    }
    datas = (guid, params) => {
        this.update(guid, { loading: true });
        const { dataKey } = this.getState(guid);
        API.Search.datas({ guid, dataKey, ...params }).then((data) => {
            const { api_status, api_errormsg } = data;
            if (api_status) {
                this.update(guid, { ...data, loading: false });
            } else {
                console.log(api_errormsg);
                this.update(guid, { loading: false });
                throw api_errormsg;
            }
        })
    }
    getState = (guid) => {
        if (guid in this.state) {
            return this.state[guid];
        } else {
            return this.state.init;
        }
    }
}

export default new SearchStore();